/**
 * random 随机数
 */
package rdm

import (
	"crypto/rand"
	"errors"
	"math/big"
)

const (
	CHARSET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)

type Rdm struct {
	Length int
}

//默认 5 位随机数
func New() *Rdm {
	return &Rdm{5}
}

func NewRdm() string {
	return NewGenerate(5)
}

func NewGenerate(i int) string {
	h := New()
	h.SetLength(i)
	r, _ := h.Generate()
	return r
}

func (h *Rdm) SetLength(i int) error {
	if i < 5 {
		return errors.New("Length must be 5 or more")
	}
	h.Length = i
	return nil
}

func (h *Rdm) Generate() (string, error) {
	var gen []rune
	l := big.NewInt(int64(len(CHARSET) - 1))
	for i := 0; i < h.Length; i++ {
		r, err := rand.Int(rand.Reader, l)
		if err != nil {
			return "", err
		}
		gen = append(gen, rune(CHARSET[r.Uint64()]))
	}
	return string(gen), nil
}
